package cc.ycws.api.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cc.ycws.core.dao.INSERTUserMapper;
import cc.ycws.core.domain.Unitdoor;
import cc.ycws.core.domain.Uploadfileto;
import cc.ycws.core.domain.countuser;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@Controller
@RequestMapping("/ssm/updownuserto")
public class UpdownusertoApi {

    @Resource
    INSERTUserMapper iNSERTUserMapper;

    /*
     * PAD上传人脸接口
     */
    @ResponseBody
    @RequestMapping(value = "/synchronizationuser", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
    public String synchronizationuser(String Imgbase, String Nuberuser, String Termofvalidity, String idnumberandto, String createtime, String registrationandtype) {
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = null;
        Uploadfileto up = new Uploadfileto();
        Date data = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss" + "01");
        String newData = dateFormat.format(data);
        String str = ".jpg";
        String yfilename2 = "/home/apache-tomcat-7.0.47/webapps/image/upload/" + newData + str;
        String yfilename = "https://wwl.ycws.cc/image/upload/" + newData + str;
        String cardnumber = Nuberuser;
        String idnumber = Termofvalidity;
        String ydetailed = null;
        List<Unitdoor> list3 = iNSERTUserMapper.selectPadfin(idnumberandto);
        String yaddress = list3.get(0).getAddress();
        String ydetailedto = list3.get(0).getNumber();
        List<Uploadfileto> list2 = iNSERTUserMapper.selectuserone(cardnumber, yaddress);

        if (list3.size() == 0) {//判断PAD是否绑定了
            msg = "400";
            map.put("id", msg);
            JSONObject json = new JSONObject(map);
            return json.toString();
        } else {
            String miu = "all";

            if (ydetailedto.equals(miu)) {//判断小区在用快速绑定的时候，是有独立的单元楼PAD
                ydetailed = "";
            } else {
                ydetailed = ydetailedto;
            }
            if (list2.size() == 0) {//卡号不重复
                BASE64Decoder deone = new BASE64Decoder();
                try {
                    //解密
                    byte[] b = deone.decodeBuffer(Imgbase);
                    //转换数据
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {
                            b[i] += 256;
                        }
                    }
                    OutputStream out = new FileOutputStream(yfilename2);
                    out.write(b);
                    out.flush();
                    out.close();
                    Date data2 = new Date();
                    SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String updatetime = dateFormat2.format(data2);
                    String yindex = "1";
                    String examine = "1";
                    iNSERTUserMapper.insertuser(yfilename, cardnumber, idnumber, yaddress, yindex, createtime, examine, updatetime, registrationandtype, ydetailed);//插入数据
                    up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
                    msg = String.valueOf(up.getYid());
                } catch (FileNotFoundException e) {
                    msg = "0";
                    e.printStackTrace();
                } catch (IOException e) {
                    msg = "0";
                    e.printStackTrace();
                } catch (Exception e) {
                    msg = "0";
                    e.printStackTrace();
                }
                map.put("id", msg);
                new JSONObject();
                JSONObject json = new JSONObject(map);
                return json.toString();
            } else {
                //卡号重复
                BASE64Decoder deone = new BASE64Decoder();
                try {
                    //解密
                    byte[] b = deone.decodeBuffer(Imgbase);
                    //转换数据
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {
                            b[i] += 256;
                        }
                    }
                    OutputStream out = new FileOutputStream(yfilename2);
                    out.write(b);
                    out.flush();
                    out.close();
                    Date data2 = new Date();
                    SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String updatetime = dateFormat2.format(data2);
                    String yindex = "1";
                    String examine = "1";
                    String cardnumberandrepeat = "repeat";
                    iNSERTUserMapper.insertuserandks(yfilename, cardnumber, idnumber, yaddress, yindex, createtime, examine, updatetime, registrationandtype, cardnumberandrepeat, ydetailed);//插入数据
                    up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
                    msg = String.valueOf(up.getYid());
                } catch (FileNotFoundException e) {
                    msg = "0";
                    e.printStackTrace();
                } catch (IOException e) {
                    msg = "0";
                    e.printStackTrace();
                } catch (Exception e) {
                    msg = "0";
                    e.printStackTrace();
                }
                map.put("id", msg);
                new JSONObject();
                JSONObject json = new JSONObject(map);
                return json.toString();
            }
        }
    }


    /*
     * ---PAD普通注册上传人脸接口
     */
    @ResponseBody
    @RequestMapping(value = "/CommonandSynchronizationuser", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
    public String CommonandSynchronizationuser(String Imgbase, String Nuberuser, String Termofvalidity, String idnumberandto, String createtime, String registrationandtype, String yname) {
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = null;
        Uploadfileto up = new Uploadfileto();
        Date data = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss" + "01");
        String newData = dateFormat.format(data);
        String str = ".jpg";
        String yfilename2 = "/home/apache-tomcat-7.0.47/webapps/image/upload/" + newData + str;
        String yfilename = "https://wwl.ycws.cc/image/upload/" + newData + str;
        String cardnumber = Nuberuser;
        String idnumber = Termofvalidity;
        List<Unitdoor> list3 = iNSERTUserMapper.selectPadfin(idnumberandto);
        String yaddress = list3.get(0).getAddress();
        String ydetailedyo = list3.get(0).getNumber();
        String ydetailed = null;
        String miu = "all";
        if (ydetailedyo.equals(miu)) {
            ydetailed = "大门";
        } else {
            ydetailed = ydetailedyo;
        }
        if (list3.size() == 0) {//判断PAD是否绑定了
            msg = "400";
            map.put("id", msg);
            new JSONObject();
            JSONObject json = new JSONObject(map);
            return json.toString();
        } else {
            String uf = "";
            String ut = null;
            if (cardnumber.equals(uf) || cardnumber.equals(ut)) {//上传的用户是没有带卡号的
                BASE64Decoder deone = new BASE64Decoder();
                try {
                    //解密
                    byte[] b = deone.decodeBuffer(Imgbase);
                    //转换数据
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {
                            b[i] += 256;
                        }
                    }
                    OutputStream out = new FileOutputStream(yfilename2);
                    out.write(b);
                    out.flush();
                    out.close();
                    Date data2 = new Date();
                    SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String updatetime = dateFormat2.format(data2);
                    String yindex = "1";
                    String examine = "1";
                    iNSERTUserMapper.insertuserandyname(yfilename, cardnumber, idnumber, yaddress, yindex, createtime, examine, updatetime, registrationandtype, yname, ydetailed);//插入数据
                    up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
                    msg = String.valueOf(up.getYid());
                } catch (FileNotFoundException e) {
                    msg = "0";
                    e.printStackTrace();
                } catch (IOException e) {
                    msg = "0";
                    e.printStackTrace();
                } catch (Exception e) {
                    msg = "0";
                    e.printStackTrace();
                }
                map.put("id", msg);
                new JSONObject();
                JSONObject json = new JSONObject(map);
                return json.toString();
            } else {//-----------------------用户注册带了卡号
                List<Uploadfileto> list2 = iNSERTUserMapper.selectuserone(cardnumber, yaddress);
                if (list2.size() == 0) {//---------------------------卡号不重复
                    BASE64Decoder deone = new BASE64Decoder();
                    try {
                        //解密
                        byte[] b = deone.decodeBuffer(Imgbase);
                        //转换数据
                        for (int i = 0; i < b.length; ++i) {
                            if (b[i] < 0) {
                                b[i] += 256;
                            }
                        }
                        OutputStream out = new FileOutputStream(yfilename2);
                        out.write(b);
                        out.flush();
                        out.close();
                        Date data2 = new Date();
                        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String updatetime = dateFormat2.format(data2);
                        String yindex = "1";
                        String examine = "1";
                        iNSERTUserMapper.insertuserandyname(yfilename, cardnumber, idnumber, yaddress, yindex, createtime, examine, updatetime, registrationandtype, yname, ydetailed);//插入数据
                        up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
                        msg = String.valueOf(up.getYid());
                    } catch (FileNotFoundException e) {
                        msg = "0";
                        e.printStackTrace();
                    } catch (IOException e) {
                        msg = "0";
                        e.printStackTrace();
                    } catch (Exception e) {
                        msg = "0";
                        e.printStackTrace();
                    }
                    map.put("id", msg);
                    new JSONObject();
                    JSONObject json = new JSONObject(map);
                    return json.toString();

                } else {
                    //卡号重复 要给特定的一个标识 repeat
                    BASE64Decoder deone = new BASE64Decoder();
                    try {
                        //解密
                        byte[] b = deone.decodeBuffer(Imgbase);
                        //转换数据
                        for (int i = 0; i < b.length; ++i) {
                            if (b[i] < 0) {
                                b[i] += 256;
                            }
                        }
                        OutputStream out = new FileOutputStream(yfilename2);
                        out.write(b);
                        out.flush();
                        out.close();
                        Date data2 = new Date();
                        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String updatetime = dateFormat2.format(data2);
                        String yindex = "1";
                        String examine = "1";
                        String cardnumberandrepeat = "repeat";
                        iNSERTUserMapper.insertuserandrepeat(yfilename, cardnumber, idnumber, yaddress, yindex, createtime, examine, updatetime, registrationandtype, cardnumberandrepeat, yname, ydetailed);//插入数据
                        up = iNSERTUserMapper.selecuser(yfilename);//查询插入的ID
                        msg = String.valueOf(up.getYid());
                    } catch (FileNotFoundException e) {
                        msg = "0";
                        e.printStackTrace();
                    } catch (IOException e) {
                        msg = "0";
                        e.printStackTrace();
                    } catch (Exception e) {
                        msg = "0";
                        e.printStackTrace();
                    }
                    map.put("id", msg);
                    new JSONObject();
                    JSONObject json = new JSONObject(map);
                    return json.toString();
                }
            }
        }
    }


    /*
     * ---PAD刷卡抓拍人脸上传
     */
    @ResponseBody
    @RequestMapping(value = "/CommonandSynchronizationusertosnapshotrecord", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
    public String CommonandSynchronizationusertosnapshotrecord(String Imgbase, String Nuberuser, String createtime, String idnumberandto) {
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = null;
        Date data = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss" + "01");
        String newData = dateFormat.format(data);
        String str = ".jpg";
        String yfilename2 = "/home/apache-tomcat-7.0.47/webapps/image/zp/" + newData + str;
        String yfilename = "https://wwl.ycws.cc/image/zp/" + newData + str;
	       /* String yfilename2="D:/"+newData+str;
	        String yfilename="D:/"+newData+str;*/
        String cardnumber = Nuberuser;//卡号
        List<Unitdoor> list3 = iNSERTUserMapper.selectPadfin(idnumberandto);//根据PAD序列号查询有没有绑定
        String yaddress = list3.get(0).getAddress();
        String ydetailedto = list3.get(0).getNumber();
        String ydetailed = null;

        if (list3.size() == 0) {//判断PAD是否绑定了
            msg = "400";
            map.put("id", msg);
            new JSONObject();
            JSONObject json = new JSONObject(map);
            return json.toString();
        } else {
            BASE64Decoder deone = new BASE64Decoder();
            try {
                //解密
                byte[] b = deone.decodeBuffer(Imgbase);
                //转换数据
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {
                        b[i] += 256;
                    }
                }
                OutputStream out = new FileOutputStream(yfilename2);
                out.write(b);
                out.flush();
                out.close();
                if (ydetailedto.equals("all")) {
                    ydetailed = "大门";
                } else {
                    ydetailed = ydetailedto;
                }
                iNSERTUserMapper.insertuserandsnapshotrecord(yfilename, cardnumber, yaddress, createtime, ydetailed);
                msg = "1";
            } catch (FileNotFoundException e) {
                msg = "0";
                e.printStackTrace();
            } catch (IOException e) {
                msg = "0";
                e.printStackTrace();
            } catch (Exception e) {
                msg = "0";
                e.printStackTrace();
            }

            map.put("id", msg);
            new JSONObject();
            JSONObject json = new JSONObject(map);
            return json.toString();

        }

    }


    @ResponseBody
    @RequestMapping(value = "/selecetusercount", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
    public String selecetusercount(String statretime, String enttime) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<countuser> listone;
        try {
            listone = iNSERTUserMapper.selectusercont(statretime, enttime);
            map.put("list", listone);
        } catch (Exception e) {
            map.put("0000", "数据查询错误");
            e.printStackTrace();
        }

        new JSONObject();
        JSONObject json = new JSONObject(map);
        return json.toString();
    }


    @ResponseBody
    @RequestMapping(value = "/synchronizationuser2", produces = "text/html;charset=UTF-8", method = RequestMethod.GET)
    public String synchronizationuser() {
        String imgFile = "C:/0/2017102715121801.jpg";//待处理的图片
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // return encoder.encode(data);//返回Base64编码过的字节数组字符串
        String Imgbase = encoder.encode(data);
        String Nuberuser = "123456";
        String Termofvalidity = "20171123";
        //String aa=doPostSelect(Imgbase, Nuberuser, Termofvalidity);
        // String a= ssss(Imgbase, Nuberuser, Termofvalidity);
        String filePath = "C:\\shuchu\\yang.txt";
        String content = encoder.encode(data);
        //String content="杨志威";
        contentToTxt(filePath, content);
        return null;
    }


    public static void contentToTxt(String filePath, String content) {
        try {
            String str = new String(); //原有txt内容
            String s1 = new String();//内容更新
            try {
                File f = new File(filePath);
	                 /*if (f.exists()) {
	                     System.out.print("文件存在");
	                 } else {
	                     System.out.print("文件不存在");
	                     f.createNewFile();// 不存在则创建
	                 } */
                BufferedReader input = new BufferedReader(new FileReader(f));

                while ((str = input.readLine()) != null) {
                    s1 += str + "\n";
                }
                //System.out.println(s1);
                input.close();
                s1 += content;

                BufferedWriter output = new BufferedWriter(new FileWriter(f));
                output.write(s1);
                output.close();
            } catch (Exception e) {
                e.printStackTrace();

            }

	        	/* 写入Txt文件
                File writename = new File(filePath); // 相对路径，如果没有则要建立一个新的output。txt文件
                writename.createNewFile(); // 创建新文件
                BufferedWriter out = new BufferedWriter(new FileWriter(writename));//true,则追加写入text文本
                //BufferedWriter out = new BufferedWriter(new FileWriter(writename));
                out.write(content); // \r\n即为换行
                out.flush(); // 把缓存区内容压入文件
                out.close(); // 最后记得关闭文件
*/
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 创建文件
     *
     * @param fileName
     * @return
     */
    public static boolean createFile(File fileName) throws Exception {
        boolean flag = false;
        try {
            if (!fileName.exists()) {
                fileName.createNewFile();
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }


}
